import React, { createRef } from 'react'

import styles from './index.module.scss'

class Sticky extends React.Component {
  childrenRef = createRef()

  placeHolderRef = createRef()

  handleScroll = () => {
    const childrenDOM = this.childrenRef.current
    const placeHolderDOM = this.placeHolderRef.current

    const { top } = placeHolderDOM.getBoundingClientRect()
    // console.log(top)
    if (top < 0) {
      childrenDOM.classList.add(styles.fixed)
      placeHolderDOM.style.height = '40px'
    } else {
      childrenDOM.classList.remove(styles.fixed)
      placeHolderDOM.style.height = '0'
    }
  }

  componentDidMount() {
    // console.log(444)
    window.addEventListener('scroll', this.handleScroll)
  }
  componentWillMount() {
    window.removeEventListener('scroll', this.handleScroll)
  }
  render() {
    return (
      <>
        <div ref={this.placeHolderRef}></div>
        <div ref={this.childrenRef}>{this.props.children}</div>
      </>
    )
  }
}

export default Sticky
